﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Collections.ObjectModel;
using System.Text;
using Microsoft.Phone.Shell;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using RestSharp;
using System.Diagnostics;

namespace unifiqAnthony
{
    public partial class ViewSuggestion : PhoneApplicationPage
    {
        private static string API_KEY = "AoetA0820tVc4COdo9bGyEKy0mBSDjoSeb9vlIRP3iC3RWibRFlwOGPGVLOUn7Fs";
        WebClient evtSgnClient, userClient;
        private string eventTitle;
        private int eventID;
        private List<EventSuggestion> evtSgnList = new List<EventSuggestion>();
        private List<DisplayEventSuggestion> displayEvtSgnList = new List<DisplayEventSuggestion>();
        //private DisplayEventSuggestion[] displayEvtSgnArr;
        //private List<RequestData> requestDataList = new List<RequestData>();
        private List<User> userList = new List<User>();

        public ViewSuggestion()
        {
            InitializeComponent();
            Loaded += MainPage_Loaded;
        }

        private void MainPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            string evtSgnURL = "http://unifiq.5kportal.com/retrieve_event_suggestion.php";
            Uri evtSgnUri = new Uri(evtSgnURL);
            evtSgnClient = new WebClient();
            evtSgnClient.AllowReadStreamBuffering = true;

            evtSgnClient.DownloadStringCompleted += evtSgnClient_DownloadStringCompleted;
            evtSgnClient.DownloadProgressChanged += evtSgnClient_DownloadProgressChanged;

            evtSgnClient.DownloadStringAsync(evtSgnUri);

            string userURL = "http://unifiq.5kportal.com/retrieve_all_users.php";
            Uri userUri = new Uri(userURL);
            userClient = new WebClient();
            userClient.AllowReadStreamBuffering = true;

            userClient.DownloadStringCompleted += userClient_DownloadStringCompleted;
            userClient.DownloadProgressChanged += userClient_DownloadProgressChanged;

            userClient.DownloadStringAsync(userUri);

        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            eventTitle = NavigationContext.QueryString["eventTitle"];
            eventID = Convert.ToInt32(NavigationContext.QueryString["eventID"]);

            PageTitle.Text = eventTitle;
        }


        private void evtSgnClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Cancelled == false & e.Error == null)
            {
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(e.Result));
                ObservableCollection<EventSuggestion> list = new ObservableCollection<EventSuggestion>();
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ObservableCollection<EventSuggestion>));
                list = (ObservableCollection<EventSuggestion>)serializer.ReadObject(ms);

                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].eventID == eventID)
                    {
                        evtSgnList.Add(list[i]);
                    }
                }

            }

        }

        private void evtSgnClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {

        }

        private void userClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Cancelled == false & e.Error == null)
            {
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(e.Result));
                ObservableCollection<User> list = new ObservableCollection<User>();
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ObservableCollection<User>));
                list = (ObservableCollection<User>)serializer.ReadObject(ms);

                foreach (User user in list)
                {
                    userList.Add(user);
                }

                set_suggestion_lb();
            }

        }

        private void userClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {

        }

        private void set_suggestion_lb()
        {
            for (int a = 0; a < evtSgnList.Count; a++)
            {
                int pos = 0;
                for (int b = 0; b < userList.Count; b++)
                {
                    if (evtSgnList[a].userID == userList[b].uid)
                    {
                        pos = b;
                        break;
                    }
                }

                DateTime nullDateTime = new DateTime(0001, 1, 1, 0, 0, 0);
                string date, time, location, comment;

                if ((evtSgnList[a].date.Date.CompareTo(nullDateTime.Date)) == 0)
                {
                    date = "N/A";
                }
                else
                {
                    date = evtSgnList[a].date.ToShortDateString();
                }

                if ((evtSgnList[a].time.TimeOfDay.CompareTo(nullDateTime.TimeOfDay)) == 0)
                {
                    time = "N/A";
                }
                else
                {
                    time = evtSgnList[a].time.ToShortTimeString();
                }

                if (evtSgnList[a].comment == "NULL")
                {
                    comment = "N/A";
                }
                else
                {
                    comment = evtSgnList[a].comment;
                }

                if (evtSgnList[a].latitude == 0)
                {
                    location = "N/A";
                }
                else
                {
                    location = "Loading location...";
                }

                displayEvtSgnList.Add(new DisplayEventSuggestion(userList[pos].name, date, time, location, comment));
            }

            suggestion_lb.ItemsSource = displayEvtSgnList;
            for (int i = 0; i < evtSgnList.Count; i++)
            {
                if (evtSgnList[i].latitude != 0)
                {
                    string locationURL = "https://dev.virtualearth.net/REST/v1/Locations/" + evtSgnList[i].latitude.ToString() + "," + evtSgnList[i].longitude.ToString() + "?key=" + API_KEY;

                    var autoCompleteClient = new RestClient(locationURL);
                    var locationRequest = new RestRequest();
                    locationRequest.Method = Method.GET;
                    locationRequest.RequestFormat = DataFormat.Json;
                    autoCompleteClient.ExecuteAsync(locationRequest, response =>
                    {
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            var json = response.Content;
                            var jsonObject = JObject.Parse(json);
                            var dict = JsonConvert.DeserializeObject<RootObject>(json);
                            var resources = dict.resourceSets[0].resources;
                            foreach (var item in resources)
                            {
                                RequestData requestData = new RequestData();
                                requestData = new RequestData();
                                requestData.addressString = item.address.formattedAddress.Split(',')[0];
                                requestData.state = item.address.adminDistrict;
                                requestData.city = item.address.adminDistrict2;
                                requestData.country = item.address.countryRegion;
                                requestData.latitude = item.geocodePoints[0].coordinates[0].ToString();
                                requestData.longitude = item.geocodePoints[0].coordinates[1].ToString();
                                requestData.LocationDisplay = item.address.formattedAddress.Split(',')[0];

                                if (!string.IsNullOrWhiteSpace(item.address.adminDistrict2))
                                    requestData.LocationDisplay = requestData.LocationDisplay + ", " + item.address.adminDistrict2;
                                if (!string.IsNullOrWhiteSpace(item.address.adminDistrict))
                                    requestData.LocationDisplay = requestData.LocationDisplay + ", " + item.address.adminDistrict;

                                int temp = i - 1;
                                displayEvtSgnList[temp].location = requestData.LocationDisplay;
                                suggestion_lb.ItemsSource = null;
                                suggestion_lb.ItemsSource = displayEvtSgnList;
                            }
                        }
                    });
                }
            }
        }
    }

    [DataContract]
    public class EventSuggestion
    {
        [DataMember]
        public int id { get; set; }

        [DataMember]
        public int userID { get; set; }

        [DataMember]
        public int eventID { get; set; }

        [DataMember]
        public DateTime date { get; set; }

        [DataMember]
        public DateTime time { get; set; }

        [DataMember]
        public double latitude { get; set; }

        [DataMember]
        public double longitude { get; set; }

        [DataMember]
        public string comment { get; set; }

        public EventSuggestion(int id, int userID, int eventID, DateTime date, DateTime time, double latitude, double longitude, string comment)
        {
            this.id = id;
            this.userID = userID;
            this.eventID = eventID;
            this.date = date;
            this.time = time;
            this.latitude = latitude;
            this.longitude = longitude;
            this.comment = comment;
        }

    }

    [DataContract]
    public class User
    {
        [DataMember]
        public int uid { get; set; }

        [DataMember]
        public string name { get; set; }

        public User(int uid, string name)
        {
            this.uid = uid;
            this.name = name;
        }
    }


    public class DisplayEventSuggestion
    {
        public string username { get; set; }
        public string date { get; set; }
        public string time { get; set; }
        public string location { get; set; }
        public string comment { get; set; }

        public DisplayEventSuggestion(string username, string date, string time, string location, string comment)
        {
            this.username = username;
            this.date = date;
            this.time = time;
            this.location = location;
            this.comment = comment;
        }

    }
}